package com.hzeport.bgs22emduty.inbound.api;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.hzeport.bgs22emduty.config.SystemConfig;
import com.hzeport.bgs22emduty.config.login.LoginCompoentService;
import com.hzeport.bgs22emduty.config.login.UserInfoDetailVO;
import com.hzeport.bgs22emduty.config.systemLog.OperLog;
import com.hzeport.bgs22emduty.dto.ScreenAssessmentDTO;
import com.hzeport.bgs22emduty.dto.ScreenAssessmentSaveDTO;
import com.hzeport.bgs22emduty.entity.Appendix;
import com.hzeport.bgs22emduty.outbound.AppendixRepository;
import com.hzeport.bgs22emduty.vo.ScreenStandard.ScreenStandardsaveVO;
import com.hzeport.bgs22emduty.vo.file.FileVO;
import com.hzeport.bgs22emduty.common.base.BaseResult;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hzeport.bgs22emduty.entity.ScreenAssessment;
import com.hzeport.bgs22emduty.service.ScreenAssessmentService;
//import org.springframework.security.access.prepost.PreAuthorize;
import com.hzeport.bgs22emduty.common.utils.StringUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

/**
 * ${comments}
 *
 * @author code generator
 * @date 2023-02-14 09:39:44
 */
@RestController
@AllArgsConstructor
@RequestMapping("/screenassessment")
@Api(value = "screenassessment", tags = "考核情况管理")
@Slf4j
public class ScreenAssessmentController {

    private final ScreenAssessmentService screenAssessmentService;

    private final AppendixRepository appendixRepository;

    @Resource
    private SystemConfig systemConfig;
    @ApiOperation(value = "分页查询", notes = "分页查询")
    @PostMapping("/page")
    public BaseResult getScreenAssessmentPage(@RequestBody ScreenAssessmentDTO dto) {
        return BaseResult.ok(screenAssessmentService.page(dto));
    }

    @ApiOperation(value = "新增${comments}", notes = "新增${comments}")
    @PostMapping("save")
    @OperLog( systemName = "KHQK", description = "KHZX")
    public BaseResult save(@RequestBody ScreenAssessmentSaveDTO dto) throws Exception {
        return BaseResult.ok(screenAssessmentService.save(dto));
    }

    /**
     * 通过id查询${comments}
     * @param id id
     * @return R
     */
    @ApiOperation(value = "通过id查询", notes = "通过id查询")
    @GetMapping("/{id}")
    public BaseResult getById(@PathVariable("id") String id) {
        ScreenAssessment byId = screenAssessmentService.getById(id);
        List<FileVO> fileVOS = appendixRepository.list(new LambdaQueryWrapper<Appendix>().eq(Appendix::getRelevanceId, id))
                .stream().map(appendix -> {
                    FileVO fileVO = new FileVO();
                    BeanUtils.copyProperties(appendix,fileVO);
                    return fileVO;
                }).collect(Collectors.toList());
        ScreenAssessmentSaveDTO screenAssessmentSaveDTO = new ScreenAssessmentSaveDTO();
        BeanUtils.copyProperties(byId,screenAssessmentSaveDTO);
        screenAssessmentSaveDTO.setFiles(fileVOS);
        return BaseResult.ok(screenAssessmentSaveDTO);
    }

    @ApiOperation(value = "修改${comments}", notes = "修改${comments}")
    //@SysLog(.*)
    @PostMapping("updateById")
    @OperLog( systemName = "KHQK", description = "KHXG")
    public BaseResult updateById(@RequestBody ScreenAssessmentSaveDTO screenAssessmentSaveDTO) throws Exception {
//        if (CollectionUtils.isEmpty(screenAssessmentSaveDTO.getFiles())){
//            throw new Exception("必须传递pdf文件！");
//        }
//        FileVO file=screenAssessmentSaveDTO.getFiles().get(0);
//        if (!file.getCurrentFileName().endsWith(".pdf")){
//            throw new Exception("文件后缀名必须为pdf！");
//        }
        ScreenAssessment screenAssessment = new ScreenAssessment();
        BeanUtils.copyProperties(screenAssessmentSaveDTO,screenAssessment);
        if(StringUtils.isEmpty(screenAssessmentSaveDTO.getMainBody())){
            screenAssessment.setMainBody(screenAssessmentSaveDTO.getMainBody());
        }
        if (StringUtils.isNotEmpty(screenAssessmentSaveDTO.getId())){
            ScreenAssessment byId = screenAssessmentService.getById(screenAssessmentSaveDTO.getId());
            if (byId != null){
                screenAssessment.setRecVersion(byId.getRecVersion());
            }
        }
        screenAssessmentService.updateById(screenAssessment);
        List<FileVO> files = screenAssessmentSaveDTO.getFiles();
        List<Appendix> list = appendixRepository.list(new LambdaQueryWrapper<Appendix>().eq(Appendix::getRelevanceId,screenAssessment.getId()));
        if (CollectionUtils.isEmpty(list)) {
            if (!CollectionUtils.isEmpty(files)) {
                files.forEach(s -> {
                    String id = s.getId();
                    Appendix byId = appendixRepository.getById(id);
                    LambdaUpdateWrapper<Appendix> wrapper = new LambdaUpdateWrapper<>();
                    wrapper.eq(Appendix::getId,s.getId())
                            .set(byId != null,Appendix::getRecVersion,byId.getRecVersion()).set(Appendix::getRelevanceId,screenAssessment.getId());
                    appendixRepository.update(wrapper);
                });
            }
        }else {
            if (CollectionUtils.isEmpty(files)) {
                if (!CollectionUtils.isEmpty(list)) {
                    List<Appendix> list1 =
                            appendixRepository.lambdaQuery().eq(Appendix::getRelevanceId, screenAssessment.getId()).list();
                    for (Appendix appendix : list1) {
                        LambdaUpdateWrapper<Appendix> wrapper = new LambdaUpdateWrapper<>();
                        wrapper.set(Appendix::getRecVersion,appendix.getRecVersion()).set(Appendix::getRelevanceId,"");
                        appendixRepository.update(wrapper);
                    }
//                    appendixRepository.update(new LambdaUpdateWrapper<Appendix>().eq(Appendix::getRelevanceId, screenAssessment.getId())
//                            .set(Appendix::getRelevanceId,""));
                }
            }else {
                List<String> collect = files.stream().map(FileVO::getId).collect(Collectors.toList());
                List<String> collect3 = list.stream().map(Appendix::getId).collect(Collectors.toList());
                List<String> collect1 = collect3.stream().filter(item -> !collect.contains(item)).collect(Collectors.toList());
                appendixRepository.removeByIds(collect1);
                List<String> collect2 = collect.stream().filter(item-> !collect3.contains(item)).collect(Collectors.toList());
                collect2.forEach(s -> {
                    Appendix byId = appendixRepository.getById(s);
                    LambdaUpdateWrapper<Appendix> wrapper = new LambdaUpdateWrapper<>();
                    wrapper.eq(Appendix::getId,s)
                            .set(byId != null,Appendix::getRecVersion,byId.getRecVersion()).set(Appendix::getRelevanceId,screenAssessment.getId());
                    appendixRepository.update(wrapper);
                });
            }
        }
        return BaseResult.ok("成功");
    }

    /**
     * 通过id删除${comments}
     * @param id id
     * @return R
     */
    @ApiOperation(value = "通过id删除${comments}", notes = "通过id删除${comments}")
    //@SysLog(.*)
    @DeleteMapping("/{id}")
    @OperLog( systemName = "KHQK", description = "KHSC")
    public BaseResult removeById(@PathVariable String id) {
        screenAssessmentService.removeById(id);
        appendixRepository.remove(new LambdaQueryWrapper<Appendix>().eq(Appendix::getRelevanceId,id));
        return BaseResult.ok("成功");
    }

}
